import {
  Button,
  Flex,
  Popover,
  PopoverArrow,
  PopoverCloseButton,
  PopoverContent,
  PopoverTrigger,
  Text,
  useDisclosure,
} from '@chakra-ui/react';
import { useContext, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FaTrashAlt } from 'react-icons/fa';

import { TrainingContext } from '..';

import trainService from '@/api/train.service';
import IAIIconButton from '@/common/components/IAIIconButton';

export default function DeletePopover(props: { id: string }) {
  const { t } = useTranslation();
  const { modelChange, setModelChange } = useContext(TrainingContext);
  const { onOpen, onClose, isOpen } = useDisclosure();
  const [loading, setLoading] = useState<boolean>(false);
  const handleDelete = async () => {
    try {
      setLoading(true);
      const { code } = await trainService.deleteModel({ modelId: props.id });
      if (code === 200) {
        setModelChange && setModelChange(modelChange + 1);
        setLoading(false);
        onClose();
      }
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <Popover isOpen={isOpen} onOpen={onOpen} onClose={onClose} placement="top">
      <PopoverTrigger>
        <IAIIconButton
          label={t('training.deleteModel')}
          tooltip={t('training.deleteModel')}
          placement="top"
          colorScheme="error"
          aria-label=""
          icon={<FaTrashAlt />}
          size="xs"
          fontSize={14}
          variant="ghost"
          rounded="sm"
          _hover={{
            bg: 'base.900',
          }}
        />
      </PopoverTrigger>
      <PopoverContent rounded="base">
        <PopoverArrow />
        <PopoverCloseButton right="0" top="0" />
        <Flex direction="column" gap="4" pt="2" minW="150px">
          <Text>确定删除吗？</Text>
          <Flex gap="2" justify="flex-end">
            <Button size="xs" onClick={onClose} isDisabled={loading}>
              取消
            </Button>
            <Button
              isLoading={loading}
              size="xs"
              colorScheme="error"
              onClick={handleDelete}
            >
              确定
            </Button>
          </Flex>
        </Flex>
      </PopoverContent>
    </Popover>
  );
}
